<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>你画我猜 - 手机端</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link rel="stylesheet" href="styles/drawguess-mobile.scss"></link>        
</head>
<body>
    <div id="app">
        <div class="mobile-container">
            <!-- 连接状态 -->
            <div v-if="connectionStatus === 'disconnected'" class="connection-panel">
                <h1>你画我猜 - 手机端</h1>
                <div v-if="!tvIp" class="error-message">
                    <p>❌ 无效的连接链接</p>
                    <p>请通过电视端的二维码扫描进入</p>
                </div>
                <div v-else class="connection-info">
                    <p>正在连接到电视: {{ tvIp }}</p>
                    <div class="loading-spinner"></div>
                </div>
            </div>

            <!-- 连接中状态 -->
            <div v-else-if="connectionStatus === 'connecting'" class="connection-panel">
                <h2>正在连接到电视...</h2>
                <div class="loading-spinner"></div>
            </div>

            <!-- 已连接 - 绘画界面 -->
            <div v-else-if="connectionStatus === 'connected'" class="drawing-panel">
                <div class="game-header">
                    <h2>你画我猜</h2>
                    <button @click="disconnect" class="disconnect-btn">断开连接</button>
                </div>
                

                <!-- 顶部工具栏 -->
                <div class="top-toolbar">
                    <!-- 画笔按钮 -->
                    <button 
                        @click="isEraser = false"
                        :class="['tool-btn', { active: !isEraser }]"
                    >
                        <span class="icon">✏️</span>
                    </button>
                    
                    <!-- 橡皮擦按钮 -->
                    <button 
                        @click="isEraser = true"
                        :class="['tool-btn', { active: isEraser }]"
                    >
                        <span class="icon">🧽</span>
                    </button>
                    
                    <div class="brush-control">
                        <input 
                            type="range" 
                            min="1" 
                            max="30" 
                            v-model="brushSize"
                            class="brush-slider"
                        >
                    </div>
                    
                    <button 
                        @click="clearCanvas"
                        class="tool-btn clear-btn"
                    >
                        <span class="icon">🗑️</span>
                    </button>
                    
                    <!-- 颜色选择器下拉菜单 -->
                    <div class="color-picker-dropdown" ref="colorPickerRef">
                        <button 
                            class="color-picker-btn"
                            @click.stop="showColorPicker = !showColorPicker"
                        >
                            <span class="icon">🎨</span>
                        </button>
                        <div 
                            class="color-picker-menu"
                            :class="{ show: showColorPicker }"
                        >
                            <div 
                                v-for="color in colors" 
                                :key="color"
                                :style="{ backgroundColor: color }"
                                :class="['color-option', { active: currentColor === color && !isEraser }]"
                                @click="selectColor(color); showColorPicker = false"
                            ></div>
                        </div>
                    </div>

                    <!-- 表情选择器 -->
                    <div class="emoji-picker-dropdown" ref="emojiPickerRef">
                        <button 
                            class="emoji-picker-btn"
                            @click.stop="showEmojiPicker = !showEmojiPicker"
                        >
                            <span class="icon">😀</span>
                        </button>
                        <div 
                            class="emoji-picker-menu"
                            :class="{ show: showEmojiPicker }"
                        >
                            <div class="emoji-categories">
                                <button 
                                    v-for="(category, index) in emojiCategories" 
                                    :key="index"
                                    :class="['category-btn', { active: currentEmojiCategory === index }]"
                                    @click="currentEmojiCategory = index"
                                >
                                    {{ category.icon }}
                                </button>
                            </div>
                            <div class="emoji-grid">
                                <div 
                                    v-for="emoji in emojiCategories[currentEmojiCategory].emojis" 
                                    :key="emoji"
                                    class="emoji-option"
                                    @click="addEmojiToCanvas(emoji); showEmojiPicker = false"
                                >
                                    {{ emoji }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                

                <!-- 画布区域 -->
                <div class="canvas-wrapper">
                    <canvas 
                        ref="canvas"
                        class="drawing-canvas"
                        @touchstart="startDrawing"
                        @touchmove="draw"
                        @touchend="stopDrawing"
                        @mousedown="startDrawing"
                        @mousemove="draw"
                        @mouseup="stopDrawing"
                    ></canvas>
                </div>
                
                <!-- 底部题目显示 -->
                <div class="word-display" :class="{'has-word': currentWord}">
                    <h3 v-if="currentWord">请画出: {{ currentWord }}</h3>
                    <h3 v-else class="waiting-text">等待TV端发送题目...</h3>
                </div>
                
                <!-- 绘画者不需要猜测功能 -->
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted, onBeforeUnmount } = Vue;

        createApp({
            setup() {
                // 连接状态
                const connectionStatus = ref('disconnected');
                let ws = null;

                // 路由参数
                const roomId = ref('');
                const tvIp = ref('');

                // 游戏状态
                const currentWord = ref('');
                let connectionTimer = null;
                const lastPingTime = ref(0);

                // 绘画相关
                const canvas = ref(null);
                const ctx = ref(null);
                const isDrawing = ref(false);
                const lastX = ref(0);
                const lastY = ref(0);
                const currentColor = ref('#000000');
                const brushSize = ref(5);
                const isEraser = ref(false);
                const showColorPicker = ref(false);
                const colorPickerRef = ref(null);

                // 表情选择器相关
                const showEmojiPicker = ref(false);
                const emojiPickerRef = ref(null);
                const currentEmojiCategory = ref(0);

                // 颜色选项
                const colors = [
                    '#000000', '#FF0000', '#00FF00', '#0000FF', 
                    '#FFFF00', '#FF00FF', '#00FFFF', '#FFA500',
                    '#800080', '#FFC0CB', '#A52A2A', '#808080'
                ];

                // 表情分类数据
                const emojiCategories = [
                    {
                        icon: '😀',
                        name: '笑脸',
                        emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '🤣', '😂', '🙂', '🙃', '😉', '😊', '😇', '🥰', '😍', '🤩', '😘', '😗', '😚', '😙']
                    },
                    {
                        icon: '😢',
                        name: '情感',
                        emojis: ['😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤐']
                    },
                    {
                        icon: '🐶',
                        name: '动物',
                        emojis: ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔', '🐧', '🐦', '🐤', '🦆']
                    },
                    {
                        icon: '🍎',
                        name: '食物',
                        emojis: ['🍎', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🫐', '🍈', '🍒', '🍑', '🥭', '🍍', '🥥', '🥝', '🍅', '🍆', '🥑', '🥦', '🥒']
                    },
                    {
                        icon: '⚽',
                        name: '运动',
                        emojis: ['⚽', '🏀', '🏈', '⚾', '🥎', '🎾', '🏐', '🏉', '🥏', '🎱', '🪀', '🏓', '🏸', '🏒', '🏑', '🥍', '🏏', '🪃', '🥅', '⛳']
                    },
                    {
                        icon: '🚗',
                        name: '交通',
                        emojis: ['🚗', '🚕', '🚙', '🚌', '🚎', '🏎️', '🚓', '🚑', '🚒', '🚐', '🛻', '🚚', '🚛', '🚜', '🏍️', '🛵', '🚲', '🛴', '🛹', '🛼']
                    }
                ];

                // 点击外部关闭下拉菜单
                const handleClickOutside = (event) => {
                    if (colorPickerRef.value && !colorPickerRef.value.contains(event.target)) {
                        showColorPicker.value = false;
                    }
                    if (emojiPickerRef.value && !emojiPickerRef.value.contains(event.target)) {
                        showEmojiPicker.value = false;
                    }
                };

                const getDeviceName = () => {
                    const userAgent = navigator.userAgent;
                    let deviceName = '手机设备';
                    
                    if (userAgent.includes('iPhone')) {
                        deviceName = 'iPhone';
                    } else if (userAgent.includes('iPad')) {
                        deviceName = 'iPad';
                    } else if (userAgent.includes('Android')) {
                        deviceName = 'Android设备';
                    } else if (userAgent.includes('Windows')) {
                        deviceName = 'Windows设备';
                    } else if (userAgent.includes('Mac')) {
                        deviceName = 'Mac设备';
                    }
                    
                    const timestamp = new Date().toLocaleTimeString('zh-CN', { hour12: false });
                    return `${deviceName} (${timestamp})`;
                };

                const initConnection = async () => {
                    try {
                        connectionStatus.value = 'connecting';
                        
                        // 从URL参数获取连接信息
                        const urlParams = new URLSearchParams(window.location.search);
                        roomId.value = urlParams.get('roomId') || '';
                        tvIp.value = urlParams.get('ip') || '';
                        const port = urlParams.get('port') || '8080';

                        if (!roomId.value || !tvIp.value) {
                            alert('缺少必要的连接参数：roomId 或 ip');
                            connectionStatus.value = 'disconnected';
                            return;
                        }

                        const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
                        if (!ipRegex.test(tvIp.value)) {
                            alert(`无效的IP地址格式: ${tvIp.value}`);
                            connectionStatus.value = 'disconnected';
                            return;
                        }

                        const portNum = parseInt(port);
                        if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
                            alert(`无效的端口号: ${port}`);
                            connectionStatus.value = 'disconnected';
                            return;
                        }

                        const url = `ws://${tvIp.value}:${port}`;
                        console.log('尝试连接WebSocket:', url);
                        ws = new WebSocket(url);

                        ws.onopen = () => {
                            console.log('WebSocket连接已建立');
                            const registerMsg = {
                                type: 'register_mobile',
                                roomId: roomId.value,
                                deviceId: 'mobile-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now(),
                                deviceName: getDeviceName(),
                            };
                            console.log('发送注册消息:', registerMsg);
                            
                            let retryCount = 0;
                            const maxRetries = 3;
                            
                            const sendRegister = () => {
                                if (ws && ws.readyState === WebSocket.OPEN) {
                                    ws.send(JSON.stringify(registerMsg));
                                    retryCount++;
                                    
                                    if (retryCount < maxRetries) {
                                        setTimeout(sendRegister, 1000);
                                    }
                                }
                            };
                            
                            sendRegister();
                        };

                        ws.onmessage = (event) => {
                            try {
                                const data = JSON.parse(event.data);
                                handleSocketMessage(data);
                            } catch (e) {
                                console.error('解析消息失败', e);
                            }
                        };

                        ws.onclose = (event) => {
                            console.log('WebSocket连接关闭:', event.code, event.reason);
                            connectionStatus.value = 'disconnected';
                            ws = null;
                        };

                        ws.onerror = (error) => {
                            console.error('WebSocket连接错误:', error);
                            connectionStatus.value = 'disconnected';
                            
                            let errorMessage = 'WebSocket连接失败';
                            if (error instanceof Event && error.target) {
                                const ws = error.target;
                                if (ws.readyState === WebSocket.CLOSED) {
                                    errorMessage = '无法连接到服务器，请检查IP地址和端口号是否正确';
                                }
                            }
                            
                            alert(errorMessage);
                        };
                    } catch (e) {
                        console.error('连接失败', e);
                        connectionStatus.value = 'disconnected';
                    }
                };

                const handleSocketMessage = (data) => {
                    console.log('收到WebSocket消息:', data);
                    switch (data.type) {
                        case 'mobile_registered':
                            console.log('手机端注册成功');
                            connectionStatus.value = 'connected';
                            
                            if (ws && ws.readyState === WebSocket.OPEN) {
                                ws.send(JSON.stringify({
                                    type: 'request_word',
                                    roomId: roomId.value
                                }));
                                console.log('请求题目');
                            }
                            break;
                        case 'start_game':
                            console.log('收到题目:', data.word);
                            if (data.word) {
                                currentWord.value = data.word;
                                setTimeout(() => {
                                    sendCanvasImage();
                                }, 500);
                            } else {
                                currentWord.value = '未收到题目';
                            }
                            
                            setTimeout(() => {
                                console.log('当前题目状态:', {
                                    value: currentWord.value,
                                    element: document.querySelector('.word-display'),
                                    isConnected: connectionStatus.value === 'connected',
                                    wsState: ws?.readyState
                                });
                            }, 100);
                            
                            if (ws && ws.readyState === WebSocket.OPEN) {
                                ws.send(JSON.stringify({
                                    type: 'word_received',
                                    word: data.word,
                                    deviceId: 'mobile-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now()
                                }));
                            }
                            break;
                        case 'clear_canvas':
                            clearCanvas();
                            break;
                        case 'error':
                            console.error('服务器错误:', data.message);
                            alert('连接错误: ' + data.message);
                            break;
                        case 'pong':
                            lastPingTime.value = Date.now();
                            break;
                        case 'no_word':
                            console.warn('TV端暂无可用题目');
                            currentWord.value = '等待TV端准备题目...';
                            break;
                        default:
                            console.log('未处理的消息类型:', data.type);
                            break;
                    }
                };

                const sendMessage = (data) => {
                    try {
                        if (ws && ws.readyState === WebSocket.OPEN) {
                            const messageToSend = {
                                ...data,
                                roomId: roomId.value,
                                timestamp: Date.now()
                            };
                            ws.send(JSON.stringify(messageToSend));
                            console.log('发送消息到电视:', messageToSend);
                        } else {
                            console.error('WebSocket连接未建立，无法发送消息');
                        }
                    } catch (error) {
                        console.error('发送消息失败:', error);
                    }
                };

                const getPosition = (e) => {
                    if (!canvas.value) return { x: 0, y: 0 };
                    
                    const rect = canvas.value.getBoundingClientRect();
                    const canvasScaleX = canvas.value.width / rect.width;
                    const canvasScaleY = canvas.value.height / rect.height;

                    let clientX, clientY;
                    
                    if (e instanceof TouchEvent) {
                        const touch = e.touches[0] || e.changedTouches[0];
                        if (!touch) return { x: 0, y: 0 };
                        clientX = touch.clientX;
                        clientY = touch.clientY;
                    } else {
                        clientX = e.clientX;
                        clientY = e.clientY;
                    }

                    return {
                        x: (clientX - rect.left) * canvasScaleX,
                        y: (clientY - rect.top) * canvasScaleY
                    };
                };

                const convertToRelativeCoordinates = (x, y) => {
                    if (!canvas.value) return { x: 0, y: 0 };
                    
                    return {
                        x: x / canvas.value.width,
                        y: y / canvas.value.height
                    };
                };

                const startDrawing = (e) => {
                    e.preventDefault();
                    
                    if (!ctx.value || !canvas.value) {
                        console.error('画布上下文不存在，无法绘图');
                        return;
                    }
                    
                    isDrawing.value = true;
                    
                    const pos = getPosition(e);
                    lastX.value = pos.x;
                    lastY.value = pos.y;
                    
                    ctx.value.lineWidth = brushSize.value;
                    ctx.value.lineCap = 'round';
                    ctx.value.lineJoin = 'round';
                    ctx.value.strokeStyle = currentColor.value;
                    
                    ctx.value.beginPath();
                    ctx.value.moveTo(pos.x, pos.y);
                    
                    ctx.value.arc(pos.x, pos.y, brushSize.value / 2, 0, Math.PI * 2);
                    ctx.value.fill();
                    
                    const relativePos = convertToRelativeCoordinates(pos.x, pos.y);
                    
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        ws.send(JSON.stringify({
                            type: 'draw_data',
                            drawType: 'draw_start',
                            relativeX: relativePos.x,
                            relativeY: relativePos.y,
                            color: isEraser.value ? '#FFFFFF' : currentColor.value,
                            size: brushSize.value,
                            isEraser: isEraser.value
                        }));
                    }
                    
                    console.log('开始绘图 - 移动端坐标:', pos.x, pos.y, '- 相对坐标:', relativePos.x, relativePos.y);
                };

                const draw = (e) => {
                    if (!isDrawing.value || !ctx.value || !canvas.value) return;
                    
                    e.preventDefault();
                    
                    const pos = getPosition(e);
                    
                    ctx.value.lineWidth = brushSize.value;
                    ctx.value.lineCap = 'round';
                    ctx.value.lineJoin = 'round';
                    ctx.value.strokeStyle = isEraser.value ? '#FFFFFF' : currentColor.value;
                    
                    ctx.value.beginPath();
                    ctx.value.moveTo(lastX.value, lastY.value);
                    ctx.value.lineTo(pos.x, pos.y);
                    ctx.value.stroke();
                    
                    const relativeLastPos = convertToRelativeCoordinates(lastX.value, lastY.value);
                    const relativePos = convertToRelativeCoordinates(pos.x, pos.y);
                    
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        ws.send(JSON.stringify({
                            type: 'draw_data',
                            drawType: 'draw_move',
                            relativeLastX: relativeLastPos.x,
                            relativeLastY: relativeLastPos.y,
                            relativeX: relativePos.x,
                            relativeY: relativePos.y,
                            color: isEraser.value ? '#FFFFFF' : currentColor.value,
                            size: brushSize.value,
                            isEraser: isEraser.value
                        }));
                    }
                    
                    lastX.value = pos.x;
                    lastY.value = pos.y;
                };

                const stopDrawing = () => {
                    if (isDrawing.value) {
                        const relativePos = convertToRelativeCoordinates(lastX.value, lastY.value);
                        
                        if (ws && ws.readyState === WebSocket.OPEN) {
                            ws.send(JSON.stringify({
                                type: 'draw_data',
                                drawType: 'draw_end',
                                relativeX: relativePos.x,
                                relativeY: relativePos.y,
                                color: isEraser.value ? '#FFFFFF' : currentColor.value,
                                size: brushSize.value,
                                isEraser: isEraser.value
                            }));
                        }
                    }
                    
                    isDrawing.value = false;
                    sendCanvasImage();
                };

                const sendCanvasImage = () => {
                    if (canvas.value && ws?.readyState === WebSocket.OPEN) {
                        try {
                            const imageData = canvas.value.toDataURL('image/jpeg', 0.7);
                            ws.send(JSON.stringify({
                                type: 'image_data',
                                data: imageData,
                                timestamp: Date.now()
                            }));
                            console.log('已发送画布图像到TV端');
                        } catch (error) {
                            console.error('发送画布图像失败:', error);
                        }
                    }
                };

                const selectColor = (color) => {
                    currentColor.value = color;
                    isEraser.value = false;
                    console.log('颜色已选择:', color);
                    
                    if (ctx.value) {
                        ctx.value.strokeStyle = color;
                        console.log('绘图上下文颜色已更新:', ctx.value.strokeStyle);
                    }
                };

                const addEmojiToCanvas = (emoji) => {
                    if (!canvas.value || !ctx.value) {
                        console.error('画布上下文不存在，无法添加表情');
                        return;
                    }
                    
                    const centerX = canvas.value.width / 2;
                    const centerY = canvas.value.height / 2;
                    
                    const fontSize = Math.min(canvas.value.width, canvas.value.height) * 0.1;
                    ctx.value.font = `${fontSize}px Arial`;
                    ctx.value.textAlign = 'center';
                    ctx.value.textBaseline = 'middle';
                    
                    ctx.value.fillText(emoji, centerX, centerY);
                    
                    console.log('表情已添加到画布:', emoji);
                    
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        const relativePos = convertToRelativeCoordinates(centerX, centerY);
                        ws.send(JSON.stringify({
                            type: 'emoji_data',
                            emoji: emoji,
                            relativeX: relativePos.x,
                            relativeY: relativePos.y,
                            fontSize: fontSize,
                            timestamp: Date.now()
                        }));
                        console.log('表情数据已发送到TV端');
                    }
                    
                    setTimeout(() => {
                        sendCanvasImage();
                    }, 100);
                };

                const clearCanvas = () => {
                    if (!canvas.value || !ctx.value) return;
                    
                    ctx.value.fillStyle = '#FFFFFF';
                    ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
                    
                    sendMessage({ type: 'clear_canvas' });
                };

                const disconnect = () => {
                    sendMessage({ type: 'mobile_disconnected' });
                    
                    if (ws) {
                        ws.close();
                        ws = null;
                    }
                    
                    connectionStatus.value = 'disconnected';
                    currentWord.value = '';
                };

                const initCanvas = () => {
                    if (!canvas.value) {
                        console.error('画布元素不存在');
                        return;
                    }
                    
                    const container = canvas.value.parentElement;
                    if (!container) {
                        console.error('画布容器不存在');
                        return;
                    }
                    
                    const containerWidth = container.clientWidth - 20;
                    const maxHeight = window.innerHeight * 0.5;
                    
                    const canvasSize = Math.min(containerWidth, maxHeight);
                    
                    canvas.value.width = canvasSize;
                    canvas.value.height = canvasSize;
                    
                    ctx.value = canvas.value.getContext('2d');
                    
                    if (!ctx.value) {
                        console.error('无法获取画布上下文');
                        return;
                    }
                    
                    console.log('移动端正方形画布初始化成功，大小:', canvas.value.width, 'x', canvas.value.height);
                    
                    ctx.value.fillStyle = '#FFFFFF';
                    ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
                };

                const handleResize = () => {
                    initCanvas();
                };

                onMounted(() => {
                    const urlParams = new URLSearchParams(window.location.search);
                    roomId.value = urlParams.get('roomId') || '';
                    tvIp.value = urlParams.get('ip') || '';
                    
                    if (roomId.value && tvIp.value) {
                        initConnection();
                        
                        connectionTimer = setInterval(() => {
                            if (ws && ws.readyState === WebSocket.OPEN) {
                                if (Date.now() - lastPingTime.value > 10000) {
                                    ws.send(JSON.stringify({ type: 'ping' }));
                                    lastPingTime.value = Date.now();
                                }
                                
                                if (connectionStatus.value === 'connected' && currentWord.value) {
                                    sendCanvasImage();
                                }
                                
                                if (connectionStatus.value === 'connected' && !currentWord.value) {
                                    ws.send(JSON.stringify({ 
                                        type: 'request_word',
                                        roomId: roomId.value
                                    }));
                                    console.log('请求题目');
                                }
                            } else if (connectionStatus.value === 'connected') {
                                console.log('连接异常断开，尝试重新连接...');
                                initConnection();
                            }
                        }, 5000);
                    }
                    
                    setTimeout(() => {
                        initCanvas();
                    }, 300);
                    
                    window.addEventListener('resize', handleResize);
                    document.addEventListener('click', handleClickOutside);
                });

                onBeforeUnmount(() => {
                    if (ws) {
                        ws.close();
                        ws = null;
                    }
                    
                    if (connectionTimer) {
                        clearInterval(connectionTimer);
                        connectionTimer = null;
                    }
                    
                    window.removeEventListener('resize', handleResize);
                    document.removeEventListener('click', handleClickOutside);
                    
                    console.log('组件卸载，资源已清理');
                });

                return {
                    connectionStatus,
                    tvIp,
                    currentWord,
                    canvas,
                    isDrawing,
                    currentColor,
                    brushSize,
                    isEraser,
                    showColorPicker,
                    colorPickerRef,
                    showEmojiPicker,
                    emojiPickerRef,
                    currentEmojiCategory,
                    colors,
                    emojiCategories,
                    startDrawing,
                    draw,
                    stopDrawing,
                    selectColor,
                    addEmojiToCanvas,
                    clearCanvas,
                    disconnect
                };
            }
        }).mount('#app');
    </script>
</body>
</html>